﻿var MIN_SOUND_TIME = 800;
var AudioBase64;
var recorder = null;
var startTimestamp = null;
var stopTimestamp = null;
var stopTimer = null;
var maxTimer  = null;
var MAXLENGTH = 10000;
var player;
var recordCancel = false;
var audioTimer  = null;
var playStatu;
var updataTimer = null;
var perUpdata   = 10000;
var DataArray   = [];
var pageNo = 1;
var userInfo;
var parentData;
var oldManIndex;
var lastPath;
 

var vm = avalon.define({
	$id: 'audioData',
	Array: []
});
avalon.scan();

$('#contentBody').delegate('.message-row','tap',function(){
	console.log($(this).attr("class")) ;
	var _this = this;
	var audioIndex = $(_this).index();
	if (audioTimer) {
		clearInterval(audioTimer);		
		$('.voice-icon').css('backgroundPosition','0 0');
	}
	var params = {
		soundId : vm.Array[audioIndex].soundId
	}
	App.soundRead(params,function(data){
		console.log(JSON.stringify(data));
	})
	
	var iconIndex = 0;
	audioTimer = setInterval(function(){
		$(_this).children('.audio-part').children('.voice-icon').css('backgroundPosition',-0.65*iconIndex+'rem 0');
		iconIndex = iconIndex == 3 ? 0:iconIndex+1;		
	},300);
	
	if (vm.Array[audioIndex].soundId == 'local') {
		console.log(lastPath);
		playAudio( lastPath);
	}
	else{
		console.log(App.eplus_url + App.audioPath + vm.Array[audioIndex].soundName);
		playAudio( App.eplus_url + App.audioPath + vm.Array[audioIndex].soundName);
	}
})

$('#testBtn').on('tap', function() {
	if (updataTimer) {
		clearInterval(updataTimer)
	}
	App.showPage('audio');
});

$('#toVideo').on('tap', function() {
	if (updataTimer) {
		clearInterval(updataTimer)
	}
	App.showPage('video');
});

$('#audioBtn').delegate('.mui-icon-closeempty','tap',function(){
	$('#audioBtn').css('bottom','-7rem');
	$('.mui-bar-nav~.mui-content').css('paddingBottom','2rem');
	$('#xBtn').removeClass('mui-icon-closeempty').addClass('mui-icon-arrowthinup');
});

$('#audioBtn').delegate('.mui-icon-arrowthinup','tap',function(){
	$('#audioBtn').css('bottom','0rem');
	$('.mui-bar-nav~.mui-content').css('paddingBottom','9rem');
	$('#xBtn').removeClass('mui-icon-arrowthinup').addClass('mui-icon-closeempty');
});

document.querySelector('#audioBtn').addEventListener('drag', function(event) {
	if (event.detail.deltaY > 50) {
		$('#audioBtn').css('bottom','-7rem');
		$('.mui-bar-nav~.mui-content').css('paddingBottom','2rem');
		$('#xBtn').removeClass('mui-icon-closeempty').addClass('mui-icon-arrowthinup');
		
	}
	if (event.detail.deltaY < 50) {
		$('#audioBtn').css('bottom','0rem');
		$('.mui-bar-nav~.mui-content').css('paddingBottom','9rem');
		$('#xBtn').removeClass('mui-icon-arrowthinup').addClass('mui-icon-closeempty');
	}
})

var soundAlert = document.getElementById("sound-alert");
var audioTips = document.getElementById("audio-tips");
// 控制录音弹出框是否播放
var setSoundAlertVisable = function(show) {
		if (show) {
			soundAlert.style.display = 'block';
			soundAlert.style.opacity = 1;
		} else {
			soundAlert.style.opacity = 0;
			//  完成再真正隐藏
			setTimeout(function() {
				soundAlert.style.display = 'none';
			}, 200);
		}
	};
	
//更新语音列表
var upDataAudio = function(IsRefresh){
	IsRefresh = IsRefresh||false;
	console.log(parentData[oldManIndex].oldMenId)
	var paramsSound = {
		sysChildrenId: userInfo.sysChildrenId,
		oldManId: parentData[oldManIndex].oldMenId,
		pageNo: pageNo,
		pageSize:'20'
	}
	if (IsRefresh) {
		paramsSound.pageNo = 1;
	}

	App.soundList(paramsSound,function(data){
		plus.nativeUI.closeWaiting();
		console.log(JSON.stringify(data));
		if(data.result){
			if (parseInt(data.data.length) !==0) {
				for (var a in data.data) {
					var newCreatTime = (new Date(data.data[a].createTime).getHours()>10?new Date(data.data[a].createTime).getHours():'0'+new Date(data.data[a].createTime).getHours()) + 
					':' + (new Date(data.data[a].createTime).getMinutes()>10?new Date(data.data[a].createTime).getMinutes():'0'+new Date(data.data[a].createTime).getMinutes())
					data.data[a].newCreatTime = newCreatTime;
				}
				if (!IsRefresh) {
					pageNo += 1;
					updataAudioList(data.data.reverse());
				}
				else{
					DataArray = [];
					vm.Array  = DataArray;
					DataArray = data.data.reverse();
				}
				vm.Array  = DataArray;
				$(document).scrollTop($('#contentBody').height());
			}
			console.log( parseInt(data.data.length) ===0 )
		}
//			if (parseInt(data.data.length) !==0 && !IsRefresh) {
//				pageNo += 1;
//				updataAudioList(data.data.reverse());
//				console.log(data.data.reverse().length + ' DataArray length '+ DataArray.length)
//				DataArray = data.data.reverse().concat(DataArray);
//				console.log(' DataArray length '+ DataArray.length);
//				vm.Array  = DataArray;
//			}
//			else if(parseInt(data.data.length) !==0 && IsRefresh){
//				DataArray = [];
//				vm.Array  = DataArray;
//				DataArray = data.data.reverse();
//				var lastState = false;
//				console.log(lastPath)
//				for (var i in DataArray) {
//					if ( typeof(lastPath)!="undefined" && DataArray[i].soundName == lastPath.substr(11)  ) {
//						lastState = true;
//						break
//					}
//				}
//				if (typeof(lastPath)!="undefined" && lastState) {
//					var thisAudio ={
//						  "soundId": 'local',
//					      "imei": "358511028590575",
//					      "dataType": "TKD",
//					      "stateCode": "0",
//					      "createTime": "Nov 2, 2017 9:52:55 AM",
//					      "destination": "1",
//					      "soundName": "",
//					      "current": "01",
//					      "total": "01",
//					      "sysChildrenId": 13,
//					      "duration": 0,
//					      "delFlag": "1"
//					}
//					console.log(lastState)
//					DataArray.push(thisAudio);
//				}
//				vm.Array  = DataArray;
//				$(document).scrollTop($('#contentBody').height());
//			}
//			else if(parseInt(data.data.length) ===0&& !IsRefresh){
//				console.log(65556);
//				pageNo = pageNo -1;
//			}
//		}
	});
}


var updataAudioList = function(array){
	for(var i in array){
		for (var j in DataArray) {
			if (array[i].soundId == DataArray[j].soundId ) {
				break
			}
			else if(j == DataArray.length){
				DataArray.push(array[i].soundId);
			}
		}
	}
	vm.Array  = DataArray;
}

$(function() {
	if (typeof(localStorage.userInfo)!="undefined") {
	    userInfo = JSON.parse(localStorage.userInfo); 
		if (typeof(localStorage.parentData)!="undefined") {
		    parentData = JSON.parse(localStorage.parentData); 
		    if(typeof(localStorage.oldManIndex)!="undefined") {
		    	oldManIndex = localStorage.oldManIndex;
		    	upDataAudio(true);
				updataTimer = setInterval(function(){
//					pageNo = 1;
					upDataAudio(true);
				},perUpdata);
		    }
		}   
	}
	else{
	    mui.toast("检测不到登录状态，请重新登录！");
	}

    mui.init({
    		gestureConfig: {
    			tap: true,
    			//默认为true
    			doubletap: true,
    			//默认为false
    			longtap: true,
    			//默认为false
    			swipe: true,
    			//默认为true
    			drag: true,
    			//默认为true
    			hold: true,
    			//默认为false，不监听
    			release: false
    		},
    		beforeback: function(){
	    		if (updataTimer) {
					clearInterval(updataTimer);
				}
				//获得列表界面的webview
				var lists = plus.webview.all();
				var index = plus.webview.getWebviewById('index');
				mui.fire(index,'backIndex',{jsonStr:"true"});	
			}
    	});
    	
    	

		
    	
    var dragState2 = true;
	document.querySelector('body').addEventListener('drag', function(event) {
		if (dragState2) {			
			//往左滑
			if(event.detail.deltaX < -100){
				dragState2 = false;
			}
			//往右滑
			else if(event.detail.deltaX > 100){
				dragState2 = false;
				mui.back();
			}
			//向下
			else if(event.detail.deltaY > 100){
				dragState2 = false;
				plus.nativeUI.showWaiting("加载更多...");
				if ($('#contentBody').scrollTop() ==0) {
					console.log(pageNo)
					if (pageNo ==1) {
						pageNo += 1;
					}
					console.log(pageNo)
					upDataAudio();
					if (updataTimer) {
						clearInterval(updataTimer)
					}
					updataTimer = setInterval(function(){
						upDataAudio(true);
					},perUpdata);
				}
				console.log($('#contentBody').scrollTop())
			}
			timer = setTimeout(function(){
				dragState2 = true;
			},300);
		}	
		
	});
    	
});

mui.plusReady(function() {
//  	alert( $('#contentBody').height());
//		$('#contentBody').css('display','block');
//  	$('#contentBody').scrollTop($('#contentBody').height());
		$(document).scrollTop($('#contentBody').height());
	/**
	 * 录制语音文件转base64字符串
	 */
	// 按住录音（长按开始录音）
	document.querySelector('#recorder').addEventListener('hold', function() {
		console.log(1111)
		if (updataTimer) {
			clearInterval(updataTimer);
		}
		recordCancel = false;
		AudioBase64 = null;
		if (stopTimer) clearTimeout(stopTimer);
//		if (maxTimer) clearTimeout(maxTimer);
		maxTimer = setTimeout(function(){
			audioTips.innerHTML = "语音长度不超过"+MAXLENGTH/1000+"秒";	
			recorder.stop();
			setTimeout(function(){
				setSoundAlertVisable(false);
			},1000)
		},MAXLENGTH);
		
		audioTips.innerHTML = "手指上划，取消发送";
		soundAlert.classList.remove('rprogress-sigh');
		setSoundAlertVisable(true);

		// 获取当前设备的录音对象
		recorder = plus.audio.getRecorder();
		startTimestamp = (new Date()).getTime();

		console.log("supportedFormats:" + JSON.stringify(recorder.supportedFormats));
		recorder.record({
			format: "amr",
			filename: "_doc/audio/a_"+new Date().getHours()+new Date().getMinutes()+new Date().getSeconds()
		}, function(path) {
			if (recordCancel) return;
			lastPath = path;
			console.log("path:" + path +"lastPath"+ lastPath);
//								playAudio('_doc/audio/a_153349.amr');
			AudioBase64 = Audio2dataURL(path);
			if (waitTimer) {
				clearInterval(waitTimer);
			}
			var waitTimer = setInterval(function(){
				if (AudioBase64) {
					console.log(222222222+AudioBase64);
					var params = {
						soundName : path.substr(11),
						sysChildrenId : userInfo.sysChildrenId,
						oldManId: parentData[oldManIndex].oldMenId,
						soundData:AudioBase64
					}
					
					//上传语音的
					App.soundUpload(params,function(data){
						console.log(JSON.stringify(data));	
						if(data.result){
							mui.toast(data.msg);
							var thisAudio ={
										  "soundId": 'local',
									      "imei": "358511028590575",
									      "dataType": "TKD",
									      "stateCode": "0",
									      "createTime": "Nov 2, 2017 9:52:55 AM",
									      "destination": '0',
									      "soundName": "a_095255.amr",
									      "current": "01",
									      "total": "01",
									      "sysChildrenId": 13,
									      "duration": 0,
									      "delFlag": "1"
									}
								console.log(DataArray.length)
								DataArray.push(thisAudio);
								console.log(DataArray.length)
								vm.Array  = DataArray;
								$(document).scrollTop($('#contentBody').height());
								if (updataTimer) {
									clearInterval(updataTimer)
								}
								var counter = 0;
								var timer  = setInterval(function(){
									if (counter<3) {
										counter ++ ;
										upDataAudio(true);
									}
									else{
										clearInterval(timer);
									}
								},1500)
//								upDataAudio(true);
								updataTimer = setInterval(function(){
									upDataAudio(true);
								},perUpdata);
//							console.log(path);
//							player = plus.audio.createPlayer(lastPath);
//							setTimeout(function(){//延时获取，否则可能没有返回长度 
//						        var num = player.getDuration(); 
//						        console.log(num); 
//							        var thisAudio ={
//										  "soundId": 'local',
//									      "imei": "358511028590575",
//									      "dataType": "TKD",
//									      "stateCode": "0",
//									      "createTime": "Nov 2, 2017 9:52:55 AM",
//									      "destination": num,
//									      "soundName": "a_095255.amr",
//									      "current": "01",
//									      "total": "01",
//									      "sysChildrenId": 13,
//									      "duration": 0,
//									      "delFlag": "1"
//									}
//								console.log(DataArray.length)
//								DataArray.push(thisAudio);
//								console.log(DataArray.length)
//								vm.Array  = DataArray;
//								$(document).scrollTop($('#contentBody').height());
//								if (updataTimer) {
//									clearInterval(updataTimer)
//								}
//								var counter = 0;
//								var timer  = setInterval(function(){
//									if (counter<3) {
//										counter ++ ;
//										upDataAudio(true);
//									}
//									else{
//										clearInterval(timer);
//									}
//								},1500)
////								upDataAudio(true);
//								updataTimer = setInterval(function(){
//									upDataAudio(true);
//								},perUpdata);
//						    },1000) 
						}
						
					})
					clearInterval(waitTimer);
				}
			},200);
			
		}, function(e) {
			mui.toast("录音出现异常: " + e.message);
		});
	})

	// 释放保存（松手保存）
	document.querySelector('#recorder').addEventListener('release', function() {
		if (audioTips.classList.contains("cancel")) {
			audioTips.classList.remove("cancel");
			audioTips.innerHTML = "手指上划，取消发送";
		}
		// 判断录音时间
		stopTimestamp = (new Date()).getTime();
		if (stopTimestamp - startTimestamp < 800) {
			audioTips.innerHTML = "录音时间太短";
			soundAlert.classList.add('rprogress-sigh');
			recordCancel = true;
			stopTimer = setTimeout(function() {
				setSoundAlertVisable(false);
			}, 800);
		} else {
			setSoundAlertVisable(false);
		}
		if (updataTimer) {
			clearInterval(updataTimer)
		}
		upDataAudio(true);
		updataTimer = setInterval(function(){
			upDataAudio(true);
		},perUpdata);
		recorder.stop();
	})

	// 拖动屏幕（手指上划，取消发送）
	document.body.addEventListener('drag', function(event) {
		if (Math.abs(event.detail.deltaY) > 50) {
			if (!recordCancel) {
				recordCancel = true;
				if (!audioTips.classList.contains("cancel")) {
					audioTips.classList.add("cancel");
				}
				audioTips.innerHTML = "松开手指，取消发送";
			}
		} else {
			if (recordCancel) {
				recordCancel = false;
				if (audioTips.classList.contains("cancel")) {
					audioTips.classList.remove("cancel");
				}
				audioTips.innerHTML = "手指上划，取消发送";
			}
		}
	}, false);


	/**
	 * base64字符串转成语音文件播放
	 */
//	$('.audio-part').on('tap', function() {
//		// 语音文件dataURI
//		var base64Str = AudioBase64;
//		// 转成.amr文件播放
//		dataURL2Audio(base64Str, function(entry) {
//			console.log(155 + entry.toLocalURL())
//			var toURL = entry.toURL();
//			console.log(152 + toURL);
//			// 播放音频
//			playAudio(toURL);
//		}, function(entry) {
//			console.log(22222222222)
//		})
//	})
})

/**
 * 播放音频
 * @param {Object} path
 */

function playAudio(path) {
	if (typeof(player)!="undefined") {
		player.stop();
	}
	if (updataTimer) {
		clearInterval(updataTimer)
	}
	player = plus.audio.createPlayer(path);
	// 切换到听筒线路
	player.setRoute( plus.audio.ROUTE_EARPIECE );
	// 切换到扬声器线路
//	player.setRoute( plus.audio.ROUTE_SPEAKER );
	setTimeout(function(){//延时获取，否则可能没有返回长度 
        var num = player.getDuration(); 
        console.log(num); 
    },1000) 
	player.play(function(e) {
//		mui.toast("播放成功");
		if (audioTimer) {
			clearInterval(audioTimer);		
			$('.voice-icon').css('backgroundPosition','0 0');
			if (updataTimer) {
				clearInterval(updataTimer)
			}
			upDataAudio(true);
			updataTimer = setInterval(function(){
				upDataAudio(true);
			},perUpdata);
		}
	}, function(e) {
//		mui.toast("播放失败");
		if (audioTimer) {
			clearInterval(audioTimer);		
			$('.voice-icon').css('backgroundPosition','0 0');
			if (updataTimer) {
				clearInterval(updataTimer)
			}
			upDataAudio(true);
			updataTimer = setInterval(function(){
				upDataAudio(true);
			},perUpdata);
		}
	});
}



/**
 * 录音超时结束
 * @param {Object} path
 * void recorder.stop();
 */


/**
 * 录音语音文件转base64字符串
 * @param {Object} path
 */

function Audio2dataURL(path) {
	plus.io.resolveLocalFileSystemURL(path, function(entry) {
		entry.file(function(file) {
			var reader = new plus.io.FileReader();
			reader.onloadend = function(e) {
				console.log(e.target.result);
				AudioBase64 = e.target.result;
				return AudioBase64;
				//						dataURL2Audio(AudioBase64, function(entry){
				//							console.log(155+entry.toLocalURL())
				//							var toURL = entry.toURL();
				//							console.log(152+toURL);
				//							// 播放音频
				//						    playAudio(toURL);
				//						},function(entry){
				//							console.log(22222222222);
				//						}
				//						);
			};
			reader.readAsDataURL(file);
		}, function(e) {
			mui.toast("读写出现异常: " + e.message);
		})
	})
}

/**
 * base64字符串转成语音文件(参考http://ask.dcloud.net.cn/question/16935)
 * @param {Object} base64Str
 * @param {Object} callback
 */

function dataURL2Audio(base64Str, callback) {
	console.log(230 + base64Str)
	var base64Str = base64Str.replace('data:audio/amr;base64,', '');
	var audioName = '_doc/audio/' + (new Date()).valueOf() + '.amr';
	console.log(audioName)

	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		fs.root.getFile(audioName, {
			create: true
		}, function(entry) {
			// 获得平台绝对路径
			var fullPath = entry.fullPath;
			if (mui.os.android) {
				// 读取音频
				var Base64 = plus.android.importClass("android.util.Base64");
				var FileOutputStream = plus.android.importClass("java.io.FileOutputStream");
				try {
					var out = new FileOutputStream(fullPath);
					var bytes = Base64.decode(base64Str, Base64.DEFAULT);
					out.write(bytes);
					out.close();
					// 回调
					callback && callback(entry);
				} catch (e) {
					console.log(e.message);
				}
			} else if (mui.os.ios) {
				var NSData = plus.ios.importClass('NSData');
				var nsData = new NSData();
				nsData = nsData.initWithBase64EncodedStringoptions(base64Str, 0);
				if (nsData) {
					nsData.plusCallMethod({
						writeToFile: fullPath,
						atomically: true
					});
					plus.ios.deleteObject(nsData);
				}
				// 回调
				callback && callback(entry);
			}
		})
	})
}

function scrollToEnd(){//滚动到底部
    var h = $(document).height()-$(window).height();
    $(document).scrollTop(h); 
}